from ipywidgets import VBox,HBox,Tab,FloatText,Text,interact,Layout
import ipywidgets as widgets
import os
from autom import io,prepro,impute,postpro,opt,conv
import numpy as np
import matplotlib.pyplot as plt
import copy
import torch as t
from autom.config import cuda_if,cuda_num
from autom.opt import act_list
from autom.prepro import prepro_list
from autom.postpro import conect_method_list
from IPython.display import display
import pickle as pkl
button_style = 'info'



class main(object):
    def __init__(self):
        self.view_mode = 'img'
        self.whole_layout()
        self.run()

    def run(self):
        display(self.img_inter,self.whole)#self.img_inter,

    def whole_layout(self):
        # 全局布局，左侧为操作区，右侧为绘图区
        self.get_output()
        self.get_progress()
        self.get_imginter()
        self.get_opre()
        self.whole = VBox([self.progress,self.opre_region,self.output])
        
        
        
        #self.opre_fileselecter_list.append(self.img_inter_slider)
        
    def get_output(self):
        self.output = widgets.Output()
        self.output_count = 0
        with self.output:
            print('****************************************************************************************')
            print('CUDA is ',cuda_if,', CUDA device = ',cuda_num)
            print('['+str(self.output_count)+']: Welcome to Autom, following are the operator history:')
            self.output_count += 1

    def output_infor(self,info):
        with self.output:
            print('['+str(self.output_count)+']: '+info)
        self.output_count += 1

    def get_imginter(self):
        if type(self.__getattribute__('img_ori')) == type(None):
            self.img_display = io.load_img(save_path='./autom/start.png',mode='color')
        self.img_inter_slider = widgets.FloatSlider(value=0.5,min=0.05,max=1.0,step=0.05,
                                    continuous_update=False,layout={'width': '600px'},description='scale')
        self.img_inter_regionx1 = widgets.FloatRangeSlider(value=[0.025*2.048,0.109*2.048],
                                    min=0.0,max=1.0,step=0.001,continuous_update=False,
                                    layout={'width': '600px'},description='regionx1')
        self.img_inter_regionx2 = widgets.FloatRangeSlider(value=[0.254*2.048,0.335*2.048],
                                    min=0.0,max=1.0,step=0.001,continuous_update=False,
                                    layout={'width': '600px'},description='regionx2')
        self.img_inter_regiony1 = widgets.FloatRangeSlider(value=[0.295*2.048,0.368*2.048],
                                    min=0.0,max=1.0,step=0.001,continuous_update=False,
                                    layout={'width': '600px'},description='regiony1')
        self.img_inter_regiony2 = widgets.FloatRangeSlider(value=[0.126*2.048,0.197*2.048],
                                    min=0.0,max=1.0,step=0.001,continuous_update=False,
                                    layout={'width': '600px'},description='regiony2')
        self.img_inter = widgets.interactive_output(self.view_image,{'scale':self.img_inter_slider,
                                    'xrange1':self.img_inter_regionx1,
                                    'yrange1':self.img_inter_regiony1,
                                    'xrange2':self.img_inter_regionx2,
                                    'yrange2':self.img_inter_regiony2})
        self.img_inter_box = VBox([self.img_inter_slider,
                                    self.img_inter_regionx1,
                                    self.img_inter_regiony1,
                                    self.img_inter_regionx2,
                                    self.img_inter_regiony2])
        
    def login(self):
        pass

    def plot_img(self,scale,plot_region1,plot_region2,xrange1,yrange1,xrange2,yrange2):
        def plot_rec(xrange,yrange,c='r'):
            x0 = int(xrange[0]/skip*self.img_display.shape[1])
            x1 = int(xrange[1]/skip*self.img_display.shape[1])
            y0 = int(yrange[0]/skip*self.img_display.shape[0])
            y1 = int(yrange[1]/skip*self.img_display.shape[0])
            plt.plot([x0,x0],[y0,y1],c=c)
            plt.plot([x0,x1],[y1,y1],c=c)
            plt.plot([x1,x1],[y1,y0],c=c)
            plt.plot([x1,x0],[y0,y0],c=c)

        def plot4(img_list=[],title_list=['original img','Extended region 1','Extended region 2','Region all'],mode=4):
            plt.figure(figsize=(20*scale,20*scale))
            if mode == 4:
                plt.subplot(221)
                if img_list[0].ndim == 2:
                    plt.imshow(img_list[0][::skip,::skip],'gray')
                else:
                    plt.imshow(img_list[0][::skip,::skip,:])
                if plot_region1:
                    plot_rec(xrange1,yrange1,c='r')
                if plot_region2:
                    plot_rec(xrange2,yrange2,c='g')
                plt.title(title_list[0])
                plt.axis('off')
                plt.subplot(223)
                plt.imshow(img_list[1][::skip,::skip],'gray')
                plt.title(title_list[1])
                plt.axis('off')
                plt.subplot(224)
                plt.imshow(img_list[2][::skip,::skip],'gray')
                plt.title(title_list[2])
                plt.axis('off')
                plt.subplot(222)
            else:
                shape_img = img_list[0][::skip,::skip].shape
                color_img = np.zeros((shape_img[0],shape_img[1],3))
                color_img[:,:,0] = np.clip(img_list[1][::skip,::skip],0,1)
                color_img[:,:,1] = np.clip(img_list[2][::skip,::skip],0,1)
                color_img[:,:,2] = img_list[0][::skip,::skip]
                plt.imshow(color_img)
                plt.title(title_list[3])
                plt.axis('off')
                plt.show()

        skip = int(1//scale)
        if self.view_mode == 'img':
            plt.figure(figsize=(20*scale,20*scale))
            if self.img_display.ndim == 2:
                plt.imshow(self.img_display[::skip,::skip],'gray')
            else:
                plt.imshow(self.img_display[::skip,::skip,:])
            if plot_region1:
                plot_rec(xrange1,yrange1,c='r')
            if plot_region2:
                plot_rec(xrange2,yrange2,c='g')
            plt.axis('off')
            plt.show()
        elif self.view_mode == 'extend':
            xscale = self.img_display.shape[1]
            yscale = self.img_display.shape[0]
            region1 = [int(xrange1[0]*xscale),int(yrange1[0]*yscale),int(xrange1[1]*xscale),int(yrange1[1]*yscale)]
            region2 = [int(xrange2[0]*xscale),int(yrange2[0]*yscale),int(xrange2[1]*xscale),int(yrange2[1]*yscale)]
            extended1,extended2 = impute.ex_impute(self.img_display,region1,region2,return_cor=False,progress=self.progress)
            plot4(img_list=[self.img_display,extended1,extended2],
                    title_list=['original img','Extended region 1','Extended region 2','Region all'],mode=1)
            self.progress.value = 100
            self.extended1_img = extended1
            self.extended2_img = extended2

        elif self.view_mode == 'extract':
            if type(self.__getattribute__('img_r')) == type(None):
                self.img_r,self.pre1_img,self.pre2_img,self.cor1,self.cor2 = opt.search_r(self.extended1_img,self.extended2_img,
                                                                        self.img_display,img_mode='tree',
                                                                        thre1=self.slider_thre1.value,thre2=self.slider_thre2.value,
                                                                        return_img=True,progress=self.progress)
            else:
                self.pre1_img,self.pre2_img,self.cor1,self.cor2 = opt.search_r(self.extended1_img,self.extended2_img,
                                                            self.img_display,img_mode='tree',
                                                            thre1=self.slider_thre1.value,thre2=self.slider_thre2.value,return_img=True,searched_r=self.img_r)
            plot4(img_list=[self.img_display,self.pre1_img,self.pre2_img],
                    title_list=['original img','Extract region 1','Extract region 2','Region all'],mode=1)
        elif self.view_mode == 'mask':
            self.pre1_img = opt.cortree2img(self.img_display.shape[0],self.img_display.shape[1],self.cor1,self.img_r)
            self.pre2_img = opt.cortree2img(self.img_display.shape[0],self.img_display.shape[1],self.cor2,self.img_r)
            self.pre1_img,self.pre2_img = self.pre1_img.detach().cpu().numpy(),self.pre2_img.detach().cpu().numpy()
            plot4(img_list=[self.img_display,self.pre1_img*self.M1_dis,self.pre2_img*self.M2_dis],
                    title_list=['original img','Masked region 1','Masked region 2','Masked all'],mode=1)
        elif self.view_mode == 'links':
            plt.figure(figsize=(20*scale,20*scale))
            postpro.links(self.img_display,self.cor1,self.cor2,self.M1_dis,self.M2_dis,method=self.opre_links_list[0].value)
            self.progress.value=100
            plt.show()
        elif self.view_mode == 'extract_all':
            self.progress.value=25
            self.img_display = opt.extract_atom(self.img_thresholded,thre=self.opre_extract_all_list[0].value,
                                            sigma=self.opre_extract_all_list[1].value,r=1/self.opre_extract_all_list[2].value)
            self.img_display = self.img_display.detach().cpu().numpy()
            self.progress.value=75
            plt.figure(figsize=(20*scale,20*scale))
            if self.img_display.ndim == 2:
                plt.imshow(self.img_display[::skip,::skip],'gray')
            else:
                plt.imshow(self.img_display[::skip,::skip,:])
            plt.axis('off')
            plt.show()
            self.progress.value=100
        elif self.view_mode == 'extend_correct':
            self.progress.value = 5
            xscale = self.img_display.shape[1]
            yscale = self.img_display.shape[0]
            region1 = [int(xrange1[0]*xscale),int(yrange1[0]*yscale),int(xrange1[1]*xscale),int(yrange1[1]*yscale)]
            region2 = [int(xrange2[0]*xscale),int(yrange2[0]*yscale),int(xrange2[1]*xscale),int(yrange2[1]*yscale)]
            extended1,extended2 = impute.ex_impute(self.img_display,region1,region2,return_cor=False,progress=self.progress)
        elif self.view_mode == 'alg2':
            plt.figure(figsize=(20*scale,20*scale))
            if self.img_display.ndim == 2:
                plt.imshow(self.img_display[::skip,::skip],'gray')
            else:
                plt.imshow(self.img_display[::skip,::skip,:])
            plot_rec(self.opre_alg2_list[0].value,self.opre_alg2_list[1].value,c='r')
            plt.axis('off')
            plt.show()
        elif self.view_mode == 'clip' or self.view_mode == 'alg2link':
            plt.figure(figsize=(20*scale,20*scale))
            if self.img_display.ndim == 2:
                plt.imshow(self.img_display[::skip,::skip],'gray')
            else:
                plt.imshow(self.img_display[::skip,::skip,:])
            if self.view_mode == 'clip':
                for cor_name in self.point_dict.keys():
                    cor_now = self.point_dict[cor_name]
                    plt.scatter(cor_now[1]*self.img_display[::skip,::skip].shape[1],cor_now[0]*self.img_display[::skip,::skip].shape[0],c='r')
            else:
                pass
                #plt.scatter(self.alg2cor[:,1],self.alg2cor[:,0])
            plt.axis('off')
            plt.show()



            


    def view_image(self,scale,xrange1,yrange1,xrange2,yrange2):
        if abs(xrange1[0]-0)<1e-4 and abs(xrange1[1]-1)<1e-4 and abs(yrange1[0]-0)<1e-4 and abs(yrange1[1]-1)<1e-4 or type(self.__getattribute__('img_ori')) == type(None):
            plot_region1 = False
        else:
            plot_region1 = True
        if abs(xrange2[0]-0)<1e-4 and abs(xrange2[1]-1)<1e-4 and abs(yrange2[0]-0)<1e-4 and abs(yrange2[1]-1)<1e-4 or type(self.__getattribute__('img_ori')) == type(None):
            plot_region2 = False
        else:
            plot_region2 = True
        self.plot_img(scale,plot_region1,plot_region2,xrange1,yrange1,xrange2,yrange2)


    def get_opre(self):
        # TODO 登陆成功后login区变为opre区域
        # 操作区，七个HBox，每个HBox为一个步骤，每个HBox中含三个
        self.opre_list = []
        self.get_uploader()
        self.get_fileselecter()
        self.get_preprocess()
        self.get_imgextend()
        self.get_mask()
        self.get_links()
        self.get_extract_all()
        self.get_alg2()
        tab0 = VBox([self.img_inter_box,
                    HBox([self.opre_uploader,self.opre_fileselecter]),
                    HBox([self.opre_preprocess])])
        tab1 = VBox([self.opre_imgextend_list[0],HBox([self.slider_thre1,self.slider_thre2,self.opre_imgextend_list[1]]),
                        self.opre_mask,self.opre_links])
        tab2 = self.opre_alg2
        self.tab = widgets.Tab()
        self.tab.children = [tab0,tab1,tab2]
        self.tab.titles = ['Basic settings','Algorithm 1','Algorithm 2']
        self.opre_region = self.tab

    def get_extend_correct(self):
        def extend_correct(b):
            self.progress.description = 'Extend correct'
            self.progress.value = 0
            self.output_infor("Click 'Extend and correction' Button")
            self.view_mode = 'extend_correct'
            self.img_inter_slider.value += 1e-5
            list_now[0].icon = 'check'
        list_now = []
        list_now.append(
            widgets.Button(
                description='Extend and correction',
                layout={'width': '100px'},button_style=button_style
            ))
        list_now[0].on_click(extend_correct)
        self.opre_extend_correct = HBox(list_now)


    def get_uploader(self):
        def upload_img(b):
            uploaded_file = list_now[0].value[0]
            with open("./imgs/"+uploaded_file.name, "wb") as fp:
                fp.write(uploaded_file.content)
            self.file_list = self.get_filename()
            
        list_now = []
        list_now.append(widgets.FileUpload(
                    accept='',  # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf'
                    multiple=False  # True to accept multiple files upload else False
                ))
        list_now.append(
            widgets.Button(
                description='0.Upload',
                layout={'width': '100px'},button_style=button_style
            ))
        list_now[1].on_click(upload_img)
        self.opre_uploader = HBox(list_now)
        #self.opre_list.append(self.opre_uploader)

    def get_filename(self,mode='img'):
        def file_filter(f):
            if mode == 'img':
                if f[-4:] in ['.jpg', '.png', '.bmp','.tif']:
                    return True
                else:
                    return False
            elif mode == 'points':
                if f[-4:] in ['.pkl']:
                    return True
                else:
                    return False
        if mode == 'img':
            files = os.listdir('./imgs')
        elif mode == 'points':
            files = os.listdir('./points')
        files = list(filter(file_filter, files))
        return files

    def get_fileselecter(self):
        def open_img(b):
            self.progress.description = 'Load img'
            self.progress.value = 0
            self.output_infor("Click 'Select' Button, image name = "+list_now[0].value)
            if len(list_now) == 2:
                list_now.append(widgets.fixed(Text('Finish')))
            self.img_ori = io.load_img(save_path='./imgs/'+list_now[0].value)
            self.progress.value = 50
            self.img_display = copy.deepcopy(self.img_ori)
            self.progress.value = 75
            self.img_inter_slider.value += 1e-5
            self.progress.value = 100
            list_now[1].icon = 'check'

        self.file_list = self.get_filename()
        list_now = []
        list_now.append(
            widgets.Dropdown(
                options=self.file_list,
                description='Select image',
                layout={'width': '200px'}
            )
        )
        list_now.append(
            widgets.Button(
                description='1.Select',
                layout={'width': '100px'},button_style=button_style
            )
        )
        list_now[1].on_click(open_img)
        self.opre_fileselecter_list = list_now
        self.opre_fileselecter = HBox(self.opre_fileselecter_list)
        #self.opre_list.append(self.opre_fileselecter)

    def __getattribute__(self, name):
        try:
            r=object.__getattribute__(self, name)
        except:
            r=None
        return r

    def get_preprocess(self):
        def process_img(b):
            self.progress.description = 'Preprocess'
            self.progress.value = 0
            self.output_infor("Click 'Process' Button, Proprocess method = "+list_now[0].value+', threthold = '+str(list_now[1].value))
            if type(self.__getattribute__('img_ori')) == type(None):
                self.output_infor('<Warning>: Please select your image.')
            else:
                if list_now[0].value=='original':
                    pass
                elif list_now[0].value == 'threshold':
                    self.img_thresholded = prepro.threshold(self.img_ori,thre=list_now[1].value)
                    self.img_display = copy.deepcopy(self.img_thresholded)
                    self.img_inter_slider.value += 1e-5
                elif list_now[0].value == 'denoising':
                    pass
            self.progress.value = 100
            if list_now[2].value == 'Extend algorithm':
                self.tab.selected_index = 1
            elif list_now[2].value == 'Convolution algorithm':
                self.tab.selected_index = 2
                self.view_mode = 'alg2'
                self.img_inter_slider.value += 1e-5
            list_now[-1].icon = 'check'
        list_now = []
        list_now.append(
            widgets.Dropdown(
                options=prepro_list,
                description='Preprocess',layout={'width': '150px'}
            )
        )
        list_now.append(
            widgets.FloatSlider(
                value=0.2,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '200px'}
            )
        )
        list_now.append(
            widgets.Dropdown(
                options=['Extend algorithm','Convolution algorithm'],
                description='Algorithm',layout={'width': '150px'}
            )
        )
        list_now.append(
            widgets.Button(
                description='2.Process',
                layout={'width': '100px'},button_style=button_style
            )
        )
        list_now[-1].on_click(process_img)
        self.opre_preprocess_list = list_now
        self.opre_preprocess = HBox(self.opre_preprocess_list)
        #self.opre_list.append(self.opre_preprocess)

    def get_imgextend(self):
        def extend(b):
            self.progress.description = 'extend'
            self.progress.value = 0
            self.output_infor("Click 'Extend' Button")
            self.view_mode = 'extend'
            self.img_inter_slider.value += 1e-5
            list_now[0].icon = 'check'
        def extract(b):
            self.progress.description = 'extract'
            self.progress.value = 0
            self.output_infor("Click 'Extract' Button")
            self.view_mode = 'extract'
            self.img_inter_slider.value += 1e-5
            list_now[1].icon = 'check'
        list_now = []
        list_now.append(widgets.Button(
                                description='3.Extend',
                                layout={'width': '100px'},button_style=button_style
                            ))
        list_now.append(widgets.Button(
                                description='4.Extract',
                                layout={'width': '150px'},button_style=button_style
                            ))
        self.slider_thre1 = widgets.FloatSlider(
                value=0.3,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '300px'},description='thre1'
            )
        self.slider_thre2 = widgets.FloatSlider(
                value=0.3,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '300px'},description='thre2'
            )
        
        #list_now.append(VBox([self.slider_thre1,self.slider_thre2]))
        list_now[0].on_click(extend)
        list_now[1].on_click(extract)
        self.opre_imgextend_list = list_now#[HBox(list_now),self.slider_thre1,self.slider_thre2]
        self.opre_imgextend = VBox(self.opre_imgextend_list)
        #self.opre_list.append(self.opre_imgextend)

    def get_mask(self):
        def search_mask(b):
            # TODO 1. total step, 2. progressbar
            self.progress.description = 'mask'
            self.progress.value = 0
            self.output_infor("Click 'Search mask' Button")
            self.M1,self.M2,self.cor1,self.cor2,_ = opt.search_mask(self.pre1_img,self.pre2_img,self.img_display,mode=list_now[0].value,
                            thre1=self.slider_thre1.value,thre2=self.slider_thre2.value,
                            update_cor=list_now[2].value,searched_r=[self.img_r,self.cor1,self.cor2],
                            outputer=self.output,total_step=list_now[1].value,progress=self.progress)
            self.M1_dis,self.M2_dis = copy.deepcopy(self.M1),copy.deepcopy(self.M2)
            self.M1_dis[self.M1<self.slider_maskthre1.value] = 0
            self.M2_dis[self.M2<self.slider_maskthre2.value] = 0
            self.view_mode = 'mask'
            self.img_inter_slider.value = 0.5
            self.output_infor("Finish 'Search mask'")
            list_now[-1].icon = 'check'
        def update_mask(b):
            self.output_infor("Click 'Update mask' Button")
            self.M1_dis,self.M2_dis = copy.deepcopy(self.M1),copy.deepcopy(self.M2)
            self.M1_dis[self.M1<self.slider_maskthre1.value] = 0
            self.M2_dis[self.M2<self.slider_maskthre2.value] = 0
            self.img_inter_slider.value += 1e-5
            self.output_infor("Finish 'Update mask'")
        list_now = []
        list_now.append(
                    widgets.Dropdown(
                        options=act_list,
                        description='Algorithm',
                        layout={'width': '150px'}
                    )
        )
        list_now.append(widgets.IntSlider(
                value=500,min=0,max=10000,step=100,continuous_update=False,layout={'width': '300px'},description='iteration step'
            ))
        list_now.append(widgets.Checkbox(
                            value=False,
                            description='Update coordinates',
                            disabled=False,
                            indent=False,layout={'width': '150px'}
                        ))
        list_now.append(widgets.Button(
                                description='5.Search mask',
                                layout={'width': '150px'},button_style=button_style
                            ))
        self.slider_maskthre1 = widgets.FloatSlider(
                value=0.1,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '300px'},description='mask thre1'
            )
        self.slider_maskthre2 = widgets.FloatSlider(
                value=0.3,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '300px'},description='mask thre2'
            )
        update_button = widgets.Button(
                                description='Update mask',
                                layout={'width': '150px'},button_style=button_style
                            )
        list_now[-1].on_click(search_mask)
        update_button.on_click(update_mask)
        self.opre_mask_list = [HBox(list_now),HBox([VBox([self.slider_maskthre1,self.slider_maskthre2]),update_button])]
        self.opre_mask = VBox(self.opre_mask_list)
        #self.opre_list.append(self.opre_mask)

    def get_links(self):
        def link_atoms(b):
            self.progress.description = 'Link'
            self.progress.value = 0
            self.output_infor("Click 'Link Atoms' Button")
            self.view_mode = 'links'
            self.img_inter_slider.value += 0.01
            list_now[1].icon = 'check'
            
        list_now = []
        list_now.append(
                    widgets.Dropdown(
                        options=conect_method_list,
                        description='Rule',
                        layout={'width': '170px'}
                    )
        )
        list_now.append(widgets.Button(
                                description='6.Link Atoms',
                                layout={'width': '130px'},button_style=button_style
                            ))
        list_now[1].on_click(link_atoms)
        self.opre_links_list = list_now
        self.opre_links = HBox(list_now)
        #self.opre_list.append(self.opre_links)

    def get_extract_all(self):
        def extract_all(b):
            self.progress.description = 'Extract All'
            self.progress.value = 0
            self.output_infor("Click 'Extract All' Button")
            self.view_mode = 'extract_all'
            list_now[-1].icon = 'check'
            self.img_inter_slider.value += 1e-5
            self.output_infor("Finish 'Extract All'")
        
        list_now = []
        list_now.append(widgets.FloatSlider(
                value=0.2,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '300px'},description='thre'
            ))
        list_now.append(widgets.IntSlider(
                value=5,min=0,max=100,step=1,continuous_update=False,layout={'width': '300px'},description='sigma'
            ))
        list_now.append(widgets.IntSlider(
                value=1,min=0,max=20,step=1,continuous_update=False,layout={'width': '300px'},description='r'
            ))
        list_now.append(widgets.Button(
                                description='Extract all',
                                layout={'width': '300px'},button_style=button_style
                            ))
        list_now[-1].on_click(extract_all)
        self.opre_extract_all_list = list_now
        self.opre_extract_all = HBox([VBox(list_now[:3]),list_now[-1]])


    def get_progress(self):
        self.progress = widgets.IntProgress(
                            value=100,
                            min=0,
                            max=100,
                            description='Loading:',
                            bar_style='info', # 'success', 'info', 'warning', 'danger' or ''
                            style={'bar_color': '#498ba7'},
                            orientation='horizontal',layout={'width': '600px'}
                        )

    def get_alg2(self):
        def clip(b):
            self.progress.description = 'Clip'
            self.progress.value = 0
            self.output_infor("Click 'Clip' Button")
            self.view_mode = 'clip'
            x_start = int(self.img_ori.shape[0]*list_now[0].value[0])
            x_end = int(self.img_ori.shape[0]*list_now[0].value[1])
            y_start = int(self.img_ori.shape[1]*list_now[1].value[0])
            y_end = int(self.img_ori.shape[1]*list_now[1].value[1])
            self.img_display = copy.copy(self.img_ori[x_start:x_end,y_start:y_end])
            self.img_clip = copy.copy(self.img_ori[x_start:x_end,y_start:y_end])
            list_now[2].icon = 'check'
            self.img_inter_slider.value += 1e-5
            self.output_infor("Finish 'Clip'")
            self.progress.value = 100
        def add_point(b):
            self.progress.description = 'Add'
            self.progress.value = 0
            self.output_infor("Click 'Add' Button")
            self.view_mode = 'clip'
            list_now[3].icon = 'check'
            self.point_dict[str(len(self.point_dict.values()))] = (0.1,0.2)
            list_now[5].options = self.point_dict.keys()
            self.img_inter_slider.value += 1e-5
            self.output_infor("Finish 'Add'")
            self.progress.value = 100
        def del_point(b):
            self.progress.description = 'Delete'
            self.progress.value = 0
            self.output_infor("Click 'Delete' Button")
            self.view_mode = 'clip'
            list_now[4].icon = 'check'
            del self.point_dict[list_now[5].value]
            list_now[5].options = self.point_dict.keys()
            self.img_inter_slider.value += 1e-5
            self.output_infor("Finish 'Delete'")
            self.progress.value = 100
        def update_point(b):
            self.progress.description = 'Update'
            self.progress.value = 0
            self.output_infor("Click 'Update' Button")
            self.view_mode = 'clip'
            list_now[6].icon = 'check'
            list_now[7].value = self.point_dict[list_now[5].value][0]
            list_now[8].value = self.point_dict[list_now[5].value][1]
            list_now[5].options = self.point_dict.keys()
            self.img_inter_slider.value += 1e-5
            self.output_infor("Finish 'Update'")
            self.progress.value = 100
        def sub_point(b):
            self.progress.description = 'Sub'
            self.progress.value = 0
            self.output_infor("Click 'Submmit' Button")
            self.view_mode = 'clip'
            list_now[9].icon = 'check'
            self.point_dict[list_now[5].value] = (list_now[7].value,list_now[8].value)
            self.img_inter_slider.value += 1e-5
            self.output_infor("Finish 'Submmit'")
            self.progress.value = 100

        def links(b):
            def dict2img(my_dict,img_shape,r=3):
                img = np.zeros(img_shape)
                for point_name in my_dict.keys():
                    for indexi in range(img.shape[0]):
                        for indexj in range(img.shape[1]):
                            if (indexi-my_dict[point_name][0]*img_shape[0])**2+(indexj-my_dict[point_name][1]*img_shape[1])**2<=r**2:
                                img[indexi,indexj] = 1
                return img
            self.progress.description = 'links'
            self.progress.value = 0
            self.output_infor("Click 'Links' Button")
            conver = conv.conv_detector()
            kernel = dict2img(self.point_dict,self.img_clip.shape,r=3)
            with self.output:
                print(np.max(kernel))
            self.img_display = conver.run(kernel,self.img_ori,thre=list_now[-3].value,sigma=list_now[-2].value,progresser=self.progress,outputer=self.output)
            self.view_mode = 'alg2link'
            list_now[-1].icon = 'check'
            self.img_inter_slider.value += 1e-5
            self.output_infor("Finish 'Links'")
            self.progress.value = 100
        
        def load(b):
            self.progress.description = 'Load point'
            self.progress.value = 0
            self.output_infor("Click 'Load' Button")
            load_list[1].icon = 'check'
            with open('./points/'+load_list[0].value,'rb') as f:
                list_now[0].value,list_now[1].value,self.point_dict = pkl.load(f)
            self.output_infor("Finish 'Load'")
            self.img_inter_slider += 1e-5
            self.progress.value = 100

        def save(b):
            self.progress.description = 'Save point'
            self.progress.value = 0
            self.output_infor("Click 'Save' Button")
            load_list[3].icon = 'check'
            with open('./points/'+load_list[-2].value+'.pkl','wb') as f:
                pkl.dump([list_now[0].value,list_now[1].value,self.point_dict],f)
            load_list[0].options = self.get_filename(mode='points')
            self.output_infor("Finish 'Save'")
            self.progress.value = 100

        list_now = []
        self.point_dict = {'0':[0.27,0.2],'1':[0.6,0.23],'2':[0.44,0.48],'3':[0.76,0.5]}
        list_now.append(widgets.FloatRangeSlider(value=[0.05,0.1],
                                    min=0.0,max=1.0,step=0.001,continuous_update=False,
                                    layout={'width': '600px'},description='regionx'))
        list_now.append(widgets.FloatRangeSlider(value=[0.05,0.1],
                                    min=0.0,max=1.0,step=0.001,continuous_update=False,
                                    layout={'width': '600px'},description='regiony'))
        list_now.append(widgets.Button(
                                description='Clip',
                                layout={'width': '300px'},button_style=button_style
                            ))
        list_now[-1].on_click(clip)
        list_now.append(widgets.Button(
                                description='Add',
                                layout={'width': '150px'},button_style=button_style
                            ))
        list_now[-1].on_click(add_point)
        list_now.append(widgets.Button(
                                description='Delete',
                                layout={'width': '150px'},button_style=button_style
                            ))
        list_now[-1].on_click(del_point)
        list_now.append(
            widgets.Dropdown(
                options=self.point_dict.keys(),
                description='Point',
                layout={'width': '200px'}
            )
        )
        list_now.append(widgets.Button(
                                description='Update',
                                layout={'width': '150px'},button_style=button_style
                            ))
        list_now[-1].on_click(update_point)
        list_now.append(widgets.FloatSlider(
                value=0.2,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '300px'},description='x'
            ))
        list_now.append(widgets.FloatSlider(
                value=0.2,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '300px'},description='y'
            ))
        list_now.append(widgets.Button(
                                description='Submmit',
                                layout={'width': '150px'},button_style=button_style
                            ))
        list_now[-1].on_click(sub_point)
        list_now.append(widgets.FloatSlider(
                value=0.67,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '300px'},description='thre'
            ))
        list_now.append(widgets.FloatSlider(
                value=0.1,min=0.0,max=1.0,step=0.01,continuous_update=False,layout={'width': '300px'},description='sigma'
            ))
        list_now.append(widgets.Button(
                                description='Links',
                                layout={'width': '150px'},button_style=button_style
                            ))
        list_now[-1].on_click(links)
        self.opre_alg2_list = list_now
        load_list = []
        saved_points_list = self.get_filename(mode='points')
        load_list.append(widgets.Dropdown(
                options=saved_points_list,
                description='Saved points',
                layout={'width': '200px'}
            ))
        load_list.append(widgets.Button(
                                description='Load',
                                layout={'width': '150px'},button_style=button_style
                            ))
        load_list[-1].on_click(load)
        load_list.append(Text(value='',placeholder='Type name',description='Save name:'))
        load_list.append(widgets.Button(
                                description='Save',
                                layout={'width': '150px'},button_style=button_style
                            ))
        load_list[-1].on_click(save)
        self.opre_alg2 = VBox([HBox(load_list),HBox(list_now[:3]),HBox(list_now[3:10]),HBox(list_now[10:13])])
        

class login(object):
    # 只有登陆以后才能创建一个新的main app
    def __init__(self):
        self.user_dict = {'lzm':'hehehehehe'}
        self.get_login()
        
        display(self.oper_login)

    def login(self,b):
        if self.list_now[0].value in self.user_dict.keys():
            if self.user_dict[self.list_now[0].value] == self.list_now[1].value:
                for widgets_now in self.list_now:
                    widgets_now.close()
                self.get_app_page()
            else:
                self.list_now[-1].value = False
                self.list_now[-1].description='Wrong password'
        else:
            self.list_now[-1].value = False
            self.list_now[-1].description='Username do not exist.'

    def get_login(self):
        self.list_now = []
        self.list_now.append(widgets.Text(
                        value='',
                        placeholder='Type something',
                        description='Username:',
                        disabled=False
                    ))
        self.list_now.append(widgets.Password(
                        value='',
                        placeholder='Enter password',
                        description='Password:',
                        disabled=False
                    ))
        self.list_now.append(widgets.Button(
                        description='Login',
                        layout={'width': '300px'},button_style=button_style
                    ))
        self.list_now.append(widgets.Valid(
                            value=True,
                            description='Valid!',layout={'width': '600px'}
                        ))
        self.list_now[2].on_click(self.login)
        self.oper_login = VBox(self.list_now)

    def get_app_page(self):
        display(widgets.Button(
                                description='nmsl',
                                layout={'width': '300px'},button_style=button_style
                ))
        
